<template>
  <div class="p-6">
    <h1 class="text-2xl font-bold mb-4">语音识别测试</h1>
    
    <!-- 设备选择 -->
    <div class="mb-4">
      <h3 class="text-lg font-semibold mb-2">选择设备</h3>
      <select v-model="selectedDevice" class="w-full p-2 border rounded">
        <option value="">请选择设备</option>
        <option v-for="device in devices" :key="device.deviceId" :value="device.deviceId">
          {{ device.deviceName || device.deviceId }}
        </option>
      </select>
    </div>
    
    <!-- 录音按钮 -->
    <div class="mb-4">
      <button 
        @click="toggleRecording" 
        :disabled="!selectedDevice"
        class="px-4 py-2 bg-blue-500 text-white rounded disabled:opacity-50"
      >
        {{ isRecording ? '停止录音' : '开始录音' }}
      </button>
    </div>
    
    <!-- 识别结果 -->
    <div v-if="result" class="mb-4 p-4 bg-green-100 rounded">
      <h3 class="font-semibold">识别结果:</h3>
      <p>{{ result }}</p>
      <p class="text-sm">置信度: {{ (confidence * 100).toFixed(1) }}%</p>
    </div>
    
    <!-- 状态信息 -->
    <div class="text-sm text-gray-600">
      <p>WebSocket状态: {{ isConnected ? '已连接' : '未连接' }}</p>
      <p>录音状态: {{ isRecording ? '录音中' : '未录音' }}</p>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue';
import { deviceAPI } from '@/services/api';
import { voiceWebSocket, type VoiceRecognitionMessage } from '@/services/websocket';

const devices = ref<any[]>([]);
const selectedDevice = ref('');
const isRecording = ref(false);
const isConnected = ref(false);
const result = ref('');
const confidence = ref(0);

let mediaRecorder: MediaRecorder | null = null;

onMounted(async () => {
  await loadDevices();
  await connectWebSocket();
});

const loadDevices = async () => {
  try {
    devices.value = await deviceAPI.getUserDevices();
  } catch (error) {
    console.error('加载设备失败:', error);
  }
};

const connectWebSocket = async () => {
  try {
    await voiceWebSocket.connect();
    isConnected.value = true;
    
    voiceWebSocket.onMessage((message: VoiceRecognitionMessage) => {
      console.log('收到消息:', message);
      
      if (message.type === 'recognition_result' && message.text) {
        result.value = message.text;
        confidence.value = message.confidence || 0;
      }
    });
  } catch (error) {
    console.error('连接失败:', error);
  }
};

const toggleRecording = async () => {
  if (isRecording.value) {
    stopRecording();
  } else {
    startRecording();
  }
};

const startRecording = async () => {
  try {
    if (!selectedDevice.value) return;
    
    voiceWebSocket.selectDevice(selectedDevice.value);
    voiceWebSocket.startRecognition();
    
    const stream = await navigator.mediaDevices.getUserMedia({ audio: true });
    mediaRecorder = new MediaRecorder(stream);
    
    mediaRecorder.ondataavailable = (event) => {
      if (event.data.size > 0) {
        voiceWebSocket.sendAudioData(event.data);
      }
    };
    
    mediaRecorder.onstart = () => {
      isRecording.value = true;
    };
    
    mediaRecorder.onstop = () => {
      voiceWebSocket.stopRecognition();
      stream.getTracks().forEach(track => track.stop());
      isRecording.value = false;
    };
    
    mediaRecorder.start(200);
  } catch (error) {
    console.error('录音失败:', error);
  }
};

const stopRecording = () => {
  if (mediaRecorder && isRecording.value) {
    mediaRecorder.stop();
  }
};
</script>

<style scoped>
/* 可以添加自定义样式 */
</style>
